import React, { useState, useEffect } from "react";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import Menu from "antd/lib/menu";
import Dropdown from "antd/lib/dropdown";
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import Modal from "antd/lib/modal";
import AutoComplete from "antd/lib/auto-complete";
import zhCN from 'antd/es/locale/zh_CN';
import Employee from "@/services/employee";
import { currentUser } from "@/services/auth";
import notification from "@/services/notification";
import { useQueryShowfieldItem } from "@/services/queryshowfield";
import { AppstoreFilled, DownOutlined, UpOutlined } from "@ant-design/icons";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
import { UserProfile } from "@/components/proptypes";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import ProjectDetail from "@/services/projectdetail"

const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
function CreateProjectDetailDialog({ data, dialog }) {
  const { queryshowfielddata } = useQueryShowfieldItem("projectdetaildialog");
  const [dataLoaded, setDataLoaded] = useState(false);
  const [page, setpage] = useState(1);
  const [pagesize, setpagesize] = useState(15);
  const [total, settotal] = useState(1);
  const [code, setcode] = useState("");
  const [name, setname] = useState("");
  const [major, setmajor] = useState(data.major[0]);
  const [area, setarea] = useState(data.area);
  const [bytstatus, setbytstatus] = useState("签约");
  const [certificate, setcertificate] = useState(data.certificate[0]);
  const [location, setlocation] = useState(data.location);
  const [mobile, setmobile] = useState("");
  const [idcard, setidcard] = useState("");
  const [gdata, setgdata] = useState([]);
  const [selectedrowkeys, setselectedrowkeys] = useState([]);
  const [contacts, setcontacts] = useState("");
  const [contactsmobile, setcontactsmobile] = useState("");
  //const [employeeareadata, setemployeeareadata] = useState([]);
  //const [employeeuserdata, setemployeeuserdata] = useState([]);
  const [showall, setshowall] = useState(false);

  useEffect(() => {
    if (gdata.length < 1) {
      let param = {
        page: 1,
        pagesize: pagesize,
        code: code,
        name: name,
        major: major,
        area: area,
        bytstatus: bytstatus,
        certificate: certificate,
        location: location,
        mobile: mobile,
        idcard: idcard,
        userid: currentUser.id,
        status: 0,
        id: 0,
        datadown: false,
        projectsel: 1,
        contacts: contacts,
        contactsmobile: contactsmobile,
      }
      seldata(param);
    }

  }, [queryshowfielddata]);// eslint-disable-line react-hooks/exhaustive-deps

  function seldata(params = {}) {
    Employee.getlist(params).then(data => {
      setDataLoaded(true);
      setpage(params.page);
      setpagesize(params.pagesize);
      settotal(data.total);
      setgdata(data.data);
    });
  };

  function handlesel() {
    let param = {
      page: 1,
      pagesize: pagesize,
      code: code,
      name: name,
      major: major,
      area: area,
      bytstatus: bytstatus,
      certificate: certificate,
      location: location,
      mobile: mobile,
      idcard: idcard,
      userid: currentUser.id,
      status: 0,
      id: 0,
      datadown: false,
      projectsel: 1,
      contacts: contacts,
      contactsmobile: contactsmobile,
    }
    seldata(param);
  };
  function handleTableChange(pagination, filters, sorter) {
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagesize,
      code: code,
      name: name,
      major: major,
      area: area,
      bytstatus: bytstatus,
      certificate: certificate,
      location: location,
      mobile: mobile,
      idcard: idcard,
      userid: currentUser.id,
      id: 0,
      datadown: false,
      status: 0,
      projectsel: 1,
      contacts: contacts,
      contactsmobile: contactsmobile,
    }
    seldata(param);
  };
  function handlefieldshow() {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          dialog.close({ success: true });
        }

      }).onDismiss(() => {
      });
  }
  function rowSelection() {
    const props = {
      onChange(newSelectedRowKeys, newSselectedRows) {
        setselectedrowkeys(newSelectedRowKeys);
        // _this.setState({
        //   selectedrows: newSselectedRows,
        //   selectedrowkeys: newSelectedRowKeys,
        // });
      },
    };
    return props;
  };
  function handleadd() {
    if (selectedrowkeys.length < 1) {
      notification.error("请先选择需要关联的人才！");
      return;
    }
    if (data.id === 0) {
      notification.error("项目ID不能为空！");
      return;
    }
    let params = {
      projectid: data.id,//
      employeeids: selectedrowkeys,
      amount: data.amount,
      neednum: data.neednum,
      userid: currentUser.id,//--操作员ID
    }
    ProjectDetail.batchcreate(params)
      .then((result) => {
        dialog.close({ success: true });
      })
      .catch(error => {
        notification.error("添加失败", error.response.data.message);
      });
  }
  function handleclear(){
    setcode("");
    setname("");
    setmajor("");
    setarea("");
    setbytstatus("签约");
    setcertificate("");
    setlocation("");
    setmobile("");
    setidcard("");
  }
  const paginationProps = {
    showSizeChanger: true,
    total: total, // 数据总数
    pageSize: parseInt(pagesize), // 每页条数
    current: parseInt(page), // 当前页码
    pageSizeOptions: ["10", "20", "30", "100"],
    showTotal: ((total) => {
      return `共 ${total} 条`;
    }),
  };

  const loop = (data) => {
    let cols = [];
    if (data === undefined || data.fieldsshow === undefined) {
      return cols;
    }
    (data.fieldsshow || []).map(item => {
      let items = data.fieldsall.filter((p) => {
        return p.key === item;
      });

      cols.push({
        title: items[0].title,
        dataIndex: item,
        key: item,
        sorter: (a, b) => a[item] > b[item] ? 1 : -1
      })
      return item;
    }
    );
    return cols;
  };
  const listcolumns = loop(queryshowfielddata);
  return (
    <Modal
      {...dialog.props}
      {...({ footer: null })}
      width={document.querySelector('body').offsetWidth * 0.8}
      title="选择人员"
      okText="确定"
      cancelText="取消"

      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <ConfigProvider locale={zhCN}>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            {showall && (<><Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                毕业专业:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={major}
                  onChange={value => {
                    setmajor(value);
                  }}
                  placeholder="毕业专业"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                  {/* {(employeemajordata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))} */}
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              联系人:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={code}
                    onChange={value => {
                      setcontacts(value);
                    }}
                    placeholder="联系人"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                联系方式:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={name}
                    onChange={value => {
                      setcontactsmobile(value);
                    }}
                    placeholder="联系方式"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
            </Row>

              <Row style={{ marginBottom: 5 }}>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  人员编码:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={code}
                    onChange={value => {
                      setcode(value);
                    }}
                    placeholder="人员编码"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  人员名称:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={name}
                    onChange={value => {
                      setname(value);
                    }}
                    placeholder="人员名称"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  状态:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={bytstatus}
                    onChange={value => {
                      setbytstatus(value);
                    }}
                    placeholder="状态"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                    {/* {(employeestatusdata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))} */}
                  </AutoComplete>
                </Col>
              </Row>
              <Row style={{ marginBottom: 5 }}>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  手机:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={mobile}
                    onChange={value => {
                      setmobile(value);
                    }}
                    placeholder="手机"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  身份证号:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={idcard}
                    onChange={value => {
                      setidcard(value);
                    }}
                    placeholder="身份证号"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  社保地区:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={area}
                    onChange={value => {
                      setarea(value);
                    }}
                    placeholder="社保地区"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                    {/* {(employeeareadata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))} */}
                  </AutoComplete>
                </Col>
              </Row></>)}
            <Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                证书:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={certificate}
                  onChange={value => {
                    setcertificate(value);
                  }}
                  placeholder="证书"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                  {/* {(employeecertificatedata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))} */}
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                地区:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={location}
                  onChange={value => {
                    setlocation(value);
                  }}
                  placeholder="地区"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                  {/* {(employeeareadata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))} */}
                </AutoComplete>
              </Col>

              <Col span={8}>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => handlesel()} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => handleclear()} >
                  清空
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => { setshowall(!showall); }} >
                  {showall && (<UpOutlined />)}
                  {!showall && (<DownOutlined />)}
                  {showall ? '默认' : '更多'}
                </Button>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Button type="primary" onClick={() => {handleadd(); }} disabled={data.isnew} >
                  <i className="fa fa-plus m-r-5" />
                  关联人才
                </Button>
                <Divider type="vertical" />
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                      {currentUser.hasPermission("fieldshow") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={handlefieldshow}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
            <div>
              <Table rowKey='id'
                rowClassName={(record, index) => getRowClassName(record, index)}
                rowSelection={rowSelection()}
                columns={listcolumns}
                scroll={{ x: 'max-content' }}
                dataSource={gdata}
                pagination={paginationProps}
                loading={!dataLoaded}
                onChange={handleTableChange}
              />
            </div>
          </Layout>
        </Layout>
      </ConfigProvider>
    </Modal>
  );
}
CreateProjectDetailDialog.propTypes = {
  data: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateProjectDetailDialog);
